#include "StdAfx.h"

String^ Account::ConvertServerToTime(double srvTime)
{
	long timeAsInteger = srvTime;
	double tmpTime = Convert::ToDouble(timeAsInteger);

	DateTime ^baseDate = gcnew DateTime(1970, 1, 1);
	DateTime ^result = gcnew DateTime;
	result = baseDate->Add(TimeSpan::FromSeconds(tmpTime));

	String^ delimStr = " ";
	array<Char>^ delimiter = delimStr->ToCharArray( );
	array<String^>^ words;
	String^ line = Convert::ToString(result);
	words = line->Split( delimiter );
	delimStr = ":";
	delimiter = delimStr->ToCharArray( );
	line = words[1];
	words = line->Split( delimiter );

	return words[0] + ":" + words[1] + ":" + words[2];
}

String^ Account::ConvertServerToDate(double srvTime)
{
	long timeAsInteger = srvTime;
	double tmpTime = Convert::ToDouble(timeAsInteger);

	DateTime ^baseDate = gcnew DateTime(1970, 1, 1);
	DateTime ^result = gcnew DateTime;
	result = baseDate->Add(TimeSpan::FromSeconds(tmpTime));

	String^ delimStr = " ";
	array<Char>^ delimiter = delimStr->ToCharArray( );
	array<String^>^ words;
	String^ line = Convert::ToString(result);
	words = line->Split( delimiter );

	return words[0];
}

void Account::AddToLog(String ^subject, String ^info)
{
	log->Add(subject + " - " + info);
}

int Account::GetNextFreeID()
{
	nextFreeID++;
	return nextFreeID - 1;
}

int Account::GetNextFreeOrderID()
{
	nextFreeOrderID++;
	return nextFreeOrderID - 1;
}

void Account::updateNextFreeOrderID(System::Object ^sender, AxTWSLib::_DTwsEvents_nextValidIdEvent ^e)
{
	nextFreeOrderID = e->id;
}

Account::Account(AxTWSLib::AxTws ^twsControl)
{
	this->twsControl = twsControl;
	this->twsControl->connect("127.0.0.1", 7496, 0);
	if (twsControl->serverVersion <= 0) throw "Can't connect to IB!";

	log = gcnew List<String^>();
	nextFreeID = 0;
	nextFreeOrderID = -1;
	twsControl->nextValidId += gcnew AxTWSLib::_DTwsEvents_nextValidIdEventHandler(this, &Account::updateNextFreeOrderID);
	twsControl->reqIds(1);
}